package com.kaizen.messagehandler.chat;

import com.kaizen.codec.Invocation;
import com.kaizen.dispatcher.MessageHandler;
import com.kaizen.message.chat.ChatRedirectToUserRequest;
import com.kaizen.message.chat.ChatSendResponse;
import com.kaizen.message.chat.ChatSendToOneRequest;
import com.kaizen.server.NettyChannelManager;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ChatSendToOneHandler implements MessageHandler<ChatSendToOneRequest> {

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private NettyChannelManager nettyChannelManager;

    @Override
    public void execute(Channel channel, ChatSendToOneRequest message) {
        if (message == null) {
            logger.error("msg为空 不发送");
            return;
        }
        // <1> 这里，假装直接成功
        ChatSendResponse sendResponse = new ChatSendResponse().setMsgId(message.getMsgId()).setCode(0);
        channel.writeAndFlush(new Invocation(ChatSendResponse.TYPE, sendResponse));

        // <2> 创建转发的消息，并转发到对应等user
        ChatRedirectToUserRequest sendToUserRequest = new ChatRedirectToUserRequest()
                .setFromUser(message.getFromUser())
                .setMsgId(message.getMsgId())
                .setContent(message.getContent());
        nettyChannelManager.send(message.getToUser(), new Invocation(ChatRedirectToUserRequest.TYPE, sendToUserRequest));
    }

    @Override
    public String getType() {
        return ChatSendToOneRequest.TYPE;
    }

}
